<?php


namespace app\api\service;


use app\api\model\Member;
use app\api\model\Qr;
use think\Request;

class QrCode{

    protected  $url;

    public function __construct(){
        $accessToken = new Accesstoken();
        $token = $accessToken->getToken();
        $this->url = sprintf(config('wxinfo.qrUrl'),$token['access_token']);
    }

    public function getQrCodes($openid,$type,$page = 'pages/index/index',$scene='*'){

        $qr = new Qr();

        $qrItem = $qr->where(['openid'=>$openid,'type'=>$type])->find();
        if(!empty($qrItem)){

            if(empty($qrItem->image)){
                $retFile = $this->createQr($page,$qrItem->id,$type);
                if(is_array($retFile)){
                    return json($retFile);
                }
                $qrItem->image = $retFile;
                $qrItem->save();
                return json(['code'=>1,'data'=>$qrItem->image]);
            }
            return json(['code'=>1,'data'=>$qrItem->image]);
//            return $qrItem->image;
        }

        $member = new Member();
        $memberItem = $member->getMember($openid);

        if(empty($memberItem)){
            return ['code'=>-1,'msg'=>'用户不存在或已删除'];
        }

        $qr->openid = $openid;
        $qr->type = $type;
        $qr->memberid = $memberItem->id;
        $qr->myidentity = $memberItem->identity;   //身份:1=事业合伙人,2=销售合伙人,3=会员,4=自费会员
        $qr->createtime = time();
        $qr->save();


        $retFile = $this->createQr($page,$qr->id,$type);
        if(is_array($retFile)){
            return json($retFile);
        }
        $qr->save(['image'=>$retFile],['id'=>$qr->id]);
        return json(['code'=>1,'data'=>$retFile]);
    }


    protected function createQr($page,$id,$type){
        //1.扫码成为会员(事业合伙人,销售合伙人)
        //2.扫码成为同级销售合伙人(销售合伙人)
        //3.扫码成为销售合伙人(事业合伙人)
        //4.扫码成为会员的下线(会员)

        $processData = [
            'page'=>$page,
            'scene'=> $id.','.$type  //二维码id,二维码类型
        ];

        $qrData = json_encode($processData);
        $data = https_request($this->url,$qrData);
        $tmp = json_decode($data,true);
        if(array_key_exists('errcode',$data)){
            return ['code'=>$tmp['errcode'],'msg'=>$tmp['msg']];
        }
        //将生成的图片保存到住,再将路径返回回去
        $baseUrl = Request::instance()->domain();//获取域名
        $filename = date('YmdHis').random(6).'.jpg';

        $dir = ROOT_PATH.'public/uploads/qr';
        if(!is_dir($dir)){
            @mkdir($dir,0777,true);
        }
        $file = $dir.'/'.$filename;
        $retFile = $baseUrl.'/uploads/qr/'.$filename;
        file_put_contents($file,$data);
        return $retFile;
    }



}